﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using StockTrader.FrontEnd.MarketViewer.BusinessLogic;
using Microsoft.Office.Interop.Excel;
using System.IO;
using LumenWorks.Framework.IO.Csv;

namespace StockTrader.FrontEnd.MarketViewer.DAL
{
    public partial class DataConvertion : Form
    {
        private AsyncDataProcessor processor;

        public DataConvertion(frmMain main)
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                btnImport.Enabled = false;
                ImportRptData(dtSelected.Value, txtFileName.Text, chkSingleMode.Checked);
            }
            catch
            {
                MessageBox.Show("Lỗi khi xử lý file dữ liệu.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Market file (*.xls)|*.xls"; dialog.InitialDirectory = "\\\\dc\\data\\HoSE Info\\";
            dialog.Title = "Select data file to import ...";
            if (dialog.ShowDialog() == DialogResult.OK)
                txtFileName.Text = dialog.FileName;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void ImportRptData(DateTime transDate, string sourceFile, bool SingleMode)
        {
            int importedRecord = 0;
            int errors = 0;
            try
            {
                ResetIndicators();
                ApplicationClass app = new ApplicationClass();
                Workbook book = null;
                Worksheet sheet = null;
                Range range = null;
                int[] Columns = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                try
                {
                    app.Visible = false;
                    app.ScreenUpdating = false;
                    app.DisplayAlerts = false;

                    book = app.Workbooks.Open(sourceFile, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                         , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                        , Type.Missing, Type.Missing, Type.Missing);
                    sheet = (Worksheet)book.Worksheets[1];

                    // get a range to work with
                    range = sheet.get_Range("A1", Type.Missing);
                    // get the end of values to the right (will stop at the first empty cell)
                    range = range.get_End(XlDirection.xlToRight);
                    // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                    range = range.get_End(XlDirection.xlDown);

                    // get the address of the bottom, right cell
                    string downAddress = range.get_Address(
                        false, false, XlReferenceStyle.xlA1,
                        Type.Missing, Type.Missing);

                    // Get the range, then values from a1
                    range = sheet.get_Range("A1", downAddress);
                    object[,] values = (object[,])range.Value2;
                    DALclient dac = new DALclient();
                    if (SingleMode)
                        dac.DeleteDailyOrderByDate(transDate);
                    int totalRecord = values.GetLength(0);
                    prgImport.Maximum = totalRecord;
                    UpdateLabels("Đang cập nhật dữ liệu, xin vui lòng chờ ...", totalRecord);
                    DateTime starttime = DateTime.Now;

                    for (int i = 1; i <= totalRecord; i++)
                    {
                        importedRecord++;
                        int tvlk = 0;
                        processor = new AsyncDataProcessor(
                            int.TryParse(values[i, 2].ToString().Substring(0, 3), out tvlk) ?
                                tvlk : Convert.ToInt32(values[i, 3]),
                            transDate, values[i, 2].ToString().Trim().Substring(3, 1),
                            values[i, 7].ToString().Equals("0") ? "S" : "B",
                            values[i, 1].ToString(),
                            values[i, 7].ToString().Equals("0") ?
                                Convert.ToInt32(values[i, 9]) :
                                Convert.ToInt32(values[i, 7]),
                            values[i, 7].ToString().Equals("0") ?
                                Convert.ToInt32(values[i, 9]) :
                                Convert.ToInt32(values[i, 7]),
                                Convert.ToInt32(values[i, 6]),
                            Convert.ToInt32(values[i, 5].ToString().Replace(":", string.Empty)) * 10000,
                            values[i, 2].ToString(),
                            prgImport, lblSucess, importedRecord, starttime, totalRecord, lblElapsed,
                            lblRemain, lblSpeed, lblPercent, lblStatus);
                        processor.Execute();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                    return;
                }
                finally
                {
                    range = null;
                    sheet = null;
                    if (book != null)
                        book.Close(false, Type.Missing, Type.Missing);
                    book = null;
                    if (app != null)
                        app.Quit();
                    app = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Import result", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        public void ConvertData(DateTime transDate, string sourceFile, string convertedFile)
        {
            try
            {
                string[] strArray = null;
                int importedRecord = 0;
                if ((File.Exists(sourceFile) && (MessageBox.Show(sourceFile + " sẽ được cập nhật vào CSDL!", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)))
                {
                    ResetIndicators();
                    FileInfo srcFile = new FileInfo(sourceFile);
                    int numOfRecords = (int)srcFile.Length / 100;

                    ApplicationClass app = new ApplicationClass();
                    Workbook book = null;
                    Worksheet sheet = null;
                    Range range = null;
                    int[] Columns = { 1, 2, 3, 4, 5, 6, 7, 8 };

                    try
                    {
                        app.Visible = false;
                        app.ScreenUpdating = false;
                        app.DisplayAlerts = false;

                        book = app.Workbooks.Open(sourceFile, Type.Missing, Type.Missing, Type.Missing
                                                          , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                         , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                                        , Type.Missing, Type.Missing, Type.Missing);
                        sheet = (Worksheet)book.Worksheets[1];

                        // get a range to work with
                        range = sheet.get_Range("A1", Type.Missing);
                        // get the end of values to the right (will stop at the first empty cell)
                        range = range.get_End(XlDirection.xlToRight);
                        // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                        range = range.get_End(XlDirection.xlDown);

                        // get the address of the bottom, right cell
                        string downAddress = range.get_Address(
                            false, false, XlReferenceStyle.xlA1,
                            Type.Missing, Type.Missing);

                        // Get the range, then values from a1
                        range = sheet.get_Range("A1", downAddress);
                        object[,] values = (object[,])range.Value2;
                        DALclient dac = new DALclient();
                        dac.DeleteDailyOrderByDate(transDate);
                        for (int i = 2; i <= values.GetLength(0); i++)
                        {
                            dac.InsertDailyOrder(
                                Convert.ToInt16(values[i, 1]),
                                transDate,
                                values[i, 4].ToString(),
                                values[i, 5].ToString(),
                                values[i, 6].ToString(),
                                Convert.ToInt32(values[i, 7]),
                                Convert.ToInt32(values[i, 8]),
                                Convert.ToInt32((double)values[i, 9] * 1000),
                                Convert.ToInt32(values[i, 3]));
                        }
                        MessageBox.Show("Đã cập nhật xong dữ liệu ngày " + transDate.ToString("dd/MM/yyyy"));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                    finally
                    {
                        range = null;
                        sheet = null;
                        if (book != null)
                            book.Close(false, Type.Missing, Type.Missing);
                        book = null;
                        if (app != null)
                            app.Quit();
                        app = null;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Import result", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void ImportDataFile(string fileName)
        {
            int importedRecord = 0;

            ResetIndicators();
            FileInfo srcFile = new FileInfo(fileName);
            int numOfRecords = (int)srcFile.Length / 100;
            this.Refresh();

            using (CsvReader csv = new CsvReader(new StreamReader(fileName), true, '\t'))
            {
                int fieldCount = csv.FieldCount;
                DALclient dac = new DALclient();

                csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
                while (csv.ReadNextRecord())
                {
                    importedRecord++;
                    if (importedRecord % 20 == 0)
                    {
                        //                         UpdateIndicator((int)(((float)importedRecord / (float)numOfRecords) * 100));
                    }
                    if (csv[0].Trim().Length > 0)
                        dac.InsertAllMarket(
                            csv[0].Substring(0, 10).Trim(),
                            csv[0].Substring(11, 1).Trim(),
                            csv[0].Substring(15, 8).Trim(),
                            (csv[0].Substring(26, 8).Trim().IndexOf('T') > 0) ? csv[0].Substring(26, 8).Trim() : String.Format("{0:0}", Convert.ToDecimal(csv[0].Substring(26, 8).Trim()) * 100),
                            (csv[0].Substring(35, 8).Trim().Length > 0) ? Convert.ToInt64(csv[0].Substring(35, 8).Trim()) : 0,
                            (csv[0].Substring(45, 8).Trim().Length > 0) ? Convert.ToInt64(csv[0].Substring(45, 8).Trim()) : 0, csv[0].Substring(57, 1).Trim(),
                            csv[0].Substring(61, 10).Trim(),
                            csv[0].Substring(74, 1).Trim(),
                            csv[0].Substring(79, 5).Trim(),
                            csv[0].Substring(86, 6).Trim(),
                            csv[0].Substring(92, 6).Trim());
                }
            }
            MessageBox.Show(importedRecord.ToString() + " records imported", "Result");
        }

        private void ResetIndicators()
        {
            lblElapsed.Text = "-- : -- : --";
            lblRemain.Text = "-- : -- : --";
            lblTotal.Text = "0";
            lblSucess.Text = "0";
            lblStatus.Text = string.Empty;
            lblSpeed.Text = "0";
            lblPercent.Text = "0";

            prgImport.Value = 0;
        }

        private void UpdateLabels(string status, int total)
        {
            lblStatus.Text = status;
            lblTotal.Text = total.ToString("N0");
        }

        public void GetSessionData(DateTime transDate)
        {
            int importedRecord = 0;
            try
            {
                DALclient dac = new DALclient();
                ResetIndicators();
                dac.BackupData();
                int numOfRecords = dac.CountBackupSecurities(transDate);
                dac.InitSessionData(transDate);

                List<int> list = dac.SelectStockNoByTransDate(transDate.Date);
                foreach (int item in list)
                {
                    dac.UpdateATCByStockNo(item, transDate.Date);
                    dac.UpdateATOByStockNo(item, transDate.Date);
                    dac.UpdateSession2ByStockNo(item, transDate.Date);

                    importedRecord++;
                    if (importedRecord % 2 == 0)
                    {
                        //                         UpdateIndicator(Convert.ToInt32((float)importedRecord / (float)numOfRecords * 100));
                    }
                }
                MessageBox.Show("Completed", "Import result",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Update fail. Please try gain latter!", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {
            ResetIndicators();
            btnImport.Enabled = true;
        }

        private void dtSelected_ValueChanged(object sender, EventArgs e)
        {
            ResetIndicators();
            btnImport.Enabled = true;
        }

    }
}
